import { ApiResponse, Profile, ProfileUser } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import axios from '@/utils/request'
//1. 获取用户基本信息
export function getUser(): RootThunkAction {
  return async (dispatch) => {
    const res = await axios.get<ApiResponse<ProfileUser>>('/user')
    dispatch({
      type: 'profile/getUser',
      payload: res.data.data,
    })
  }
}
// 2. 获取用户个人信息

export function getUserProfile(): RootThunkAction {
  return async (dispatch) => {
    const res = await axios.get<ApiResponse<Profile>>('/user/profile')
    dispatch({
      type: 'profile/getUserProfile',
      payload: res.data.data,
    })
  }
}
/**
 * 更新用户信息
 * @param type
 * @param value
 * @returns
 * 为了能重新渲染 使用RootThunkAction
 */
export function updateUser(type: string, value: string): RootThunkAction {
  return async (dispatch) => {
    await axios.patch('/user/profile', {
      [type]: value,
    })
    // 重新渲染数据
    dispatch(getUserProfile())
  }
}
/**
 * 上传头像
 * @param key
 * @param params
 * @returns
 */
export default function updateUserPhoto(params: FormData): RootThunkAction {
  return async (dispatch) => {
    await axios.request({
      method: 'PATCH',
      url: '/user/photo',
      data: params,
    })
    dispatch(getUserProfile())
  }
}
